package team3.photoBrowser;

import java.util.List;

import team3.photoBrowser.services.ServiceGPS;
import team3.photoBrowser.utils.MyItemizedOverlay;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

/**
 * Main Activity,
 * 
 * Start the Gps service.
 * Show the Map.(google map)
 * Allow the user to select an area to show the pictures included.
 * 
 */

public class P6_Location_Photo_BrowserActivity extends MapActivity {
    //MapActivity is a special sub-class of Activity, provided by the Maps library, which provides important map capabilities.
	
	public static String BROADCAST_ACTION = "team3.photoBrowser.broadcast";
	public static String LATITUDE = "latitude";
	public static String LONGITUDE = "longitude";
	protected MapBroadcastReceiver mBroadcastReceiver;

	public static final String PREFS_NAME = "LocationPhotoBrowserPrefs";
	protected boolean isBound = false; //Will be used for checking the status of the Service.
    protected Intent GpsIntent; //Will be the Intent of our Gps service.
    
	protected MapView mapView;
	protected List<Overlay> mapOverlays;
	protected MyItemizedOverlay itemizedOverlay;
	protected Button showPhotosButton;
	protected Button exitButton;

	protected double latitude, longitude; //Values of the Gps
	protected Intent photoActivityIntent; //Will be the Intent of the Photo Viewer activity.
	protected float topLatitude,bottomLatitude,leftLongitude,rightLongitude,
	centerLatitude,centerLongitude,latitudeSpan,longitudeSpan,radious; //Values of the map
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        SharedPreferences sharedPreferences = getSharedPreferences(PREFS_NAME, 0); //Save the variable "isBound" to recover it the next time the activity is run. 
	    isBound = sharedPreferences.getBoolean("serviceConnected", false);
	    if(!isBound){	    	
	    	GpsIntent = new Intent(this, ServiceGPS.class);
	    	startService(GpsIntent);
	    	doBindService();
	    }
	    
		mBroadcastReceiver = new MapBroadcastReceiver();
		IntentFilter filter = new IntentFilter(BROADCAST_ACTION);		
    	registerReceiver(mBroadcastReceiver, filter);
    	
    	showPhotosButton = (Button) findViewById(R.id.showPhotosButton);
    	showPhotosButton.setOnClickListener(ShowPhotosButtonListener);
    	exitButton = (Button) findViewById(R.id.exitButton);
    	exitButton.setOnClickListener(ExitButtonListener);
    	
    	Drawable drawable = this.getResources().getDrawable(R.drawable.ic_launcher); //ic_launcher is the image to show (in PROJECT_PATH/res/drawable)
    	itemizedOverlay = new MyItemizedOverlay(drawable, this);
    	
        mapView = (MapView) findViewById(R.id.mapview);
	    //Simple zoom feature built into the MapView class.
        mapView.setBuiltInZoomControls(true);

	}	
	
	/**
	 * Establish a connection with the service.  We use an explicit
	 * class name because we want a specific service implementation that
	 * we know will be running in our own process (and thus won't be
	 * supporting component replacement by other applications).
	 * 
	 */	
	protected void doBindService() {	    	
		bindService(GpsIntent, null, Context.BIND_AUTO_CREATE);
		isBound = true;
	}
	
	protected void doUnbindService() {
    	isBound = false;
	}	
	
	/**
	 * Required.
	 * 
	 * This method is required for some accounting from the Maps service 
	 * to see if you're currently displaying any route information.
	 * 
	 */
    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }  
    
    protected void drawUserPosition() {	
    	//GeoPoint coordinates are specified in microdegrees (degrees * 1e6)
    	GeoPoint point = new GeoPoint((int)(latitude * 1E6), (int)(longitude * 1E6));
    	OverlayItem overlayItem = new OverlayItem(point,"You are There!",null);

    	itemizedOverlay.clear();
    	itemizedOverlay.addOverlay(overlayItem);
        mapOverlays = mapView.getOverlays();
    	mapOverlays.add(itemizedOverlay);  
    	mapView.invalidate();
    }
    
    private boolean hasInternetConnection() {
        ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        // Test for connection
        if (connManager.getActiveNetworkInfo() != null
                && connManager.getActiveNetworkInfo().isAvailable()
                && connManager.getActiveNetworkInfo().isConnected()) {
            return true;
        } else {
            return false;
        }
    }
    
    private OnClickListener ShowPhotosButtonListener = new OnClickListener() {
        public void onClick(View v) {        	
        	if(!hasInternetConnection()){
    			Toast toast = Toast.makeText(getApplicationContext(),"No Internet Connection. Can't show photos.", Toast.LENGTH_LONG);
    		    toast.show();
    		} else {
    			
	        	calculateArea();
	        	
	        	//send the bounding box information to the photo display activity
		    	photoActivityIntent = new Intent(P6_Location_Photo_BrowserActivity.this, PhotosDisplay_Activity.class );	
	        	photoActivityIntent.putExtra("topLatitude", topLatitude);
	        	photoActivityIntent.putExtra("bottomLatitude", bottomLatitude);
	        	photoActivityIntent.putExtra("leftLongitude", leftLongitude);
	        	photoActivityIntent.putExtra("rightLongitude", rightLongitude);
	        	      	
	        	startActivity(photoActivityIntent);
    		}
        }        	
    };  
    
    private OnClickListener ExitButtonListener = new OnClickListener() {
        public void onClick(View v) {        	
        	finish();
        }        	
    };    
    
    private void calculateArea(){ //calculate the minimum and maximum latitude and longitude
    	                          //based on the google maps information
    	   
    	GeoPoint mapTopLeft = mapView.getProjection().fromPixels(0, 0);
    	topLatitude = (float) (mapTopLeft.getLatitudeE6()/1E6); //getLatitudeE6() returns the latitude of this GeoPoint in microdegrees (degrees * 1E6)
    	leftLongitude = (float) ((float)(mapTopLeft.getLongitudeE6())/1E6);
    	    	   
    	GeoPoint mapBottomRight = mapView.getProjection().fromPixels(mapView.getWidth(), mapView.getHeight());
    	bottomLatitude = (float) ((float)(mapBottomRight.getLatitudeE6())/1E6);
    	rightLongitude = (float) ((float)(mapBottomRight.getLongitudeE6())/1E6);    	
    }
    
    public class MapBroadcastReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context arg0, Intent intent) {
			
			/*Toast toast = Toast.makeText(getApplicationContext(),"onReceive reached.", Toast.LENGTH_SHORT);
			toast.show();*/
			latitude = intent.getDoubleExtra(LATITUDE, 0);
			longitude = intent.getDoubleExtra(LONGITUDE, 0);			
			drawUserPosition();
		}    	
    }	
    
    public void onResume() {
    	super.onResume();    	
    	SharedPreferences sharedPreferences = getSharedPreferences(PREFS_NAME, 0);
    	//Checks if service is running, "false" is the default return value.  
        isBound = sharedPreferences.getBoolean("serviceConnected", false);        
        if(isBound) {
        	doBindService();	
        }               
    }
    
    public void onPause() {
    	super.onPause();    	
    	// We need an Editor object to make preference changes.
        // All objects are from android.context.Context
        SharedPreferences sharedPreferences = getSharedPreferences(PREFS_NAME, 0); //We have to save the variable isBound to recover it. 
        SharedPreferences.Editor editor = sharedPreferences.edit();	 
        editor.putBoolean("serviceConnected", isBound);
        // Commit the edits!
        editor.commit();        
        if(isBound) {
        	doUnbindService();  //must unbind it before pausing activity.
        }       
    } 
    
    public void onDestroy() {
    	super.onDestroy();
    	doUnbindService();
    	unregisterReceiver(mBroadcastReceiver);
		stopService(GpsIntent);
    }
    
}